//
//  SettingViewController.m
//  XiangMuB
//
//  Created by lanou3g on 16/8/16.
//  Copyright © 2016年 lanou3g. All rights reserved.
//

#import "SettingViewController.h"

#import "NSObject+alertView.h"
#import "SDImageCache.h"
#import "UserCollectionViewCell.h"
#import "LoadViewController.h"
#import <AVOSCloud/AVOSCloud.h>
#import "loadShare.h"
#import "LoveViewController.h"
#import "BeautiyViewController.h"
#import "BaiduViewController.h"
#import "MusicsViewController.h"
#import "ShareViewController.h"
#import "YYViewController.h"
#import "PLayViewController.h"


@interface SettingViewController ()<UICollectionViewDataSource,UICollectionViewDelegate>

@property (assign ,nonatomic)BOOL logoutt;

@end

@implementation SettingViewController



//tabbar隐藏取消
-(void)viewWillAppear:(BOOL)animated

{
    [super viewWillAppear:animated];
    
    self.tabBarController.tabBar.hidden = NO;
    
    if ([loadShare shareLoad].load == YES) {
        
        
        
           [self.navigationController.navigationBar NightWithType:(UIViewColorTypeNormal)];

       // NSMutableString *documents=[NSHomeDirectory() stringByAppendingString:@"/Documents"].mutableCopy;
        
         NSString *documents=[NSHomeDirectory() stringByAppendingString:@"/Documents"];
        
       // documents = [documents stringByAppendingFormat:@"/%@.png",[loadShare shareLoad].userName].mutableCopy;
        
          documents = [documents stringByAppendingFormat:@"/%@.png",[loadShare shareLoad].userName];
        NSData *data = [[NSFileManager defaultManager] contentsAtPath:documents];
        UIImage *image = [UIImage imageWithData:data];
        
        
       
        _imageView.image = image;

        if (_imageView.image == nil) {
            _imageView.image = [UIImage imageNamed:@"man"];
        }
        
        
    }else
    {
        _imageView.image =[UIImage imageNamed:@"man"];
        
        
    }

    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
 
    
  
 self.title = @"设置";
  

    
    //初始化登录界面
    
    self.view.backgroundColor = [UIColor lightGrayColor];
 
    
    [self.view NightWithType:(UIViewColorTypeNormal)];
    //红色背景
    UILabel *lable =[[UILabel alloc] init];
    lable.frame = CGRectMake(0, 65, self.view.frame.size.width, 200);
    lable.backgroundColor = [UIColor redColor];
    lable.alpha = 0.8;
    
    [self.view addSubview:lable];
    
    
    //头像
    _imageView =[[UIImageView alloc] init];
    
    
    _imageView.frame = CGRectMake((self.view.frame.size.width - 80)/2, 95, 80, 80);
    _imageView.backgroundColor =[UIColor whiteColor];
    self.imageView.layer.cornerRadius = _imageView.frame.size.width/2;
    self.imageView.layer.masksToBounds = YES;
    [self.view addSubview:_imageView];
    
    
    if ([loadShare shareLoad].load == YES) {
        
        
        NSMutableString *documents=[NSHomeDirectory() stringByAppendingString:@"/Documents"].mutableCopy;
        
        documents = [documents stringByAppendingFormat:@"/%@.png",[loadShare shareLoad].userName].mutableCopy;
        
        
        NSString *str =[NSString stringWithString:documents];
        
        
        NSData *data = [[NSFileManager defaultManager] contentsAtPath:str];
        UIImage *image = [UIImage imageWithData:data];
              
        _imageView.image = image;

        
        if (_imageView.image == nil) {
            _imageView.image = [UIImage imageNamed:@"man"];
        }
        
        
    }else
    {
        _imageView.image =[UIImage imageNamed:@"man"];
        
        
    }

    
    
    
   //相机按钮
    UIButton *photo = [UIButton buttonWithType:(UIButtonTypeCustom)];
    
    [photo setTitleColor:[UIColor blackColor]forState:UIControlStateNormal];
    
  
    photo.frame = CGRectMake((self.view.frame.size.width - 80)/2+75, 150, 30, 30);
    
    [photo addTarget:self action:@selector(photoAction) forControlEvents:(UIControlEventTouchUpInside)];
    
    [photo setBackgroundImage:[UIImage imageNamed:@"camera"] forState:(UIControlStateNormal)];
    
    
    [self.view addSubview:photo];
    
    
    
    

    
    
    //赢积分 抢大礼品!
    UILabel *lable1 =[[UILabel alloc] init];
    lable1.frame = CGRectMake((self.view.frame.size.width -120)/2, 220,120 , 20);
    lable1.text = @"赢积分 抢大礼品!";
    lable1.font = [UIFont systemFontOfSize:15];
    lable1.textColor = [UIColor yellowColor];
    
    [self.view addSubview:lable1];
    
    //设置按钮
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"3"] style:(UIBarButtonItemStylePlain) target:self action:@selector(Action:)];
    
    
    //分页控制器
    UISegmentedControl *seg =[[UISegmentedControl alloc] initWithItems:@[@"真心树洞",@"软件推广"]];
    seg.frame = CGRectMake(0, 295, self.view.frame.size.width, 60);
    seg.backgroundColor = [UIColor colorWithRed:192.0f/255.0f  green:192.0f/255.0f  blue:192.0f/255.0f  alpha:0.5];
    [seg addTarget:self action:@selector(segAct:) forControlEvents:(UIControlEventValueChanged)];
    

    seg.tintColor = [UIColor redColor];
    
    [self.view addSubview:seg];
    
    
    
    
    //collectionview
    UICollectionViewFlowLayout *flowout =[[UICollectionViewFlowLayout alloc] init];
    flowout.itemSize = CGSizeMake(85, 85);
    
    
    //设置行间距
    flowout.minimumInteritemSpacing = 20;
    flowout.scrollDirection = UICollectionViewScrollDirectionVertical;
    
    flowout.sectionInset = UIEdgeInsetsMake(40, 1, 20, 1);
    
    UICollectionView *collrctionview =[[UICollectionView alloc] initWithFrame:CGRectMake(0, 350, self.view.frame.size.width, 230) collectionViewLayout:flowout];
    collrctionview.backgroundColor =[UIColor whiteColor];
    collrctionview.delegate = self;
    collrctionview.dataSource = self;
    collrctionview.backgroundColor =[UIColor whiteColor];
    [collrctionview NightWithType:UIViewColorTypeClear];
    [self.view addSubview:collrctionview];
    
    [collrctionview registerClass:[UserCollectionViewCell class] forCellWithReuseIdentifier:@"cell"];
    
    
    //立即登录Button
    _loadButton =[UIButton buttonWithType:(UIButtonTypeCustom)];
    
    [_loadButton addTarget:self action:@selector(loadAction) forControlEvents:(UIControlEventTouchUpInside)];
    [_loadButton setTintColor:[UIColor whiteColor]];
    
   // [_loadButton setTitle:@"立即登录" forState:(UIControlStateNormal)];
    _loadButton.frame = CGRectMake((self.view.frame.size.width -100)/2, 180, 100, 30);
    
    [self.view addSubview:_loadButton];
    
    
    //立即登录
    
    if ([loadShare shareLoad].load == YES) {
        
      
        
        [self load];
    }
    
    else
    {
     
        
        [self logout];
    }

    
}
//摄像头图片点击方法
-(void)photoAction
{
   
    if ([loadShare shareLoad].load == NO ||_logoutt == YES) {
        
       
        
    }else{
    
    
    
    UIAlertController *alert =[UIAlertController alertControllerWithTitle:nil message:@"提示" preferredStyle:(UIAlertControllerStyleActionSheet)];
    
    UIAlertAction *action1 =[UIAlertAction actionWithTitle:@"相机" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
        
        
        UIImagePickerController *pick =[[UIImagePickerController alloc] init];
        if ([UIImagePickerController isSourceTypeAvailable:  UIImagePickerControllerSourceTypeCamera]) {
            
            pick.sourceType = UIImagePickerControllerSourceTypeCamera;
            pick.allowsEditing = YES;
            
            pick.delegate = self;
            [self presentViewController:pick animated:YES completion:nil];
        }else
        {
            NSLog(@"相机不可用");
        }
        
        
        
        
        
        
        
    }];
    
    UIAlertAction *action2 =[UIAlertAction actionWithTitle:@"相册" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
        
        UIImagePickerController *pick =[[UIImagePickerController alloc] init];
        
        if ([UIImagePickerController isSourceTypeAvailable:  UIImagePickerControllerSourceTypePhotoLibrary]) {
            
            pick.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
            
            
            pick.allowsEditing = YES;
            pick.delegate = self;
            [self presentViewController:pick animated:YES completion:nil];
            
            
            
        }else
        {
            NSLog(@"相册不可用");
        }
        
        
        
        
    }];
    
    UIAlertAction *action3 =[UIAlertAction actionWithTitle:@"取消" style:(UIAlertActionStyleCancel) handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    
    
    [alert addAction:action1];
    [alert addAction:action2];
    [alert addAction:action3];
    
    [self presentViewController:alert animated:YES completion:nil];
    
    }
    
}
//相册相机的代理方法

-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
    
    NSString *type =[info objectForKey:UIImagePickerControllerMediaType];
    
    //判断选择的是否是图片,这个 public.image和public.movie是固定的字段.
    if ([type isEqualToString:@"public.image"]) {
        
        UIImage *image =[info objectForKey:UIImagePickerControllerOriginalImage];
        
        if (picker.sourceType==UIImagePickerControllerSourceTypeCamera) {
            UIImageWriteToSavedPhotosAlbum(image, self, nil, nil);
        }
        [self.imageView setImage:image];
        
        //这里再加个写入到本地的方案
        //获取写入的文件夹
        NSString *documents=[NSHomeDirectory() stringByAppendingString:@"/Documents"];
        
   
        //将 image 转换为 data
        NSData *data;
        if (UIImagePNGRepresentation(image)) {
            data=UIImagePNGRepresentation(image);
        }
        else
            data=UIImageJPEGRepresentation(image, 1.0);
        NSFileManager *filemanager=[NSFileManager defaultManager];
       
     documents = [documents stringByAppendingFormat:@"/%@.png",[loadShare shareLoad].userName];
        
        

        
        [filemanager createFileAtPath:documents contents:data attributes:nil];
        
        
        
        
        
        NSLog(@"%@",documents);
      
        
    }
    //判断选择的是否是视频
    if ([type isEqualToString:@"public.movie"]) {
        
    }
    [picker dismissViewControllerAnimated:false completion:nil];
    
    
    
    
    
    
}

-(void)segAct:(UISegmentedControl *)sender
{
    switch (sender.selectedSegmentIndex) {
        case 0:{
            LoveViewController *love = [LoveViewController new];
            [self.navigationController pushViewController:love animated:YES];


        }
    break;
            
        case 1:{
            
            
            ShareViewController *share =[ShareViewController new];
            [self.navigationController pushViewController:share animated:YES];

        }
            break;
            
            
            
        default:
            break;
    }
}



//
////真心话点击事件
//-(void)firstAction{
//    }
////推广点击事件
//-(void)secondAction
//{
//   }

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return 8;
}

-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    
    UserCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
    
    cell.backgroundColor = [UIColor colorWithRed:192.0f/255.0f  green:192.0f/255.0f  blue:192.0f/255.0f  alpha:0.2];
    
    
    switch (indexPath.row) {
        case 0:
            
            cell.view.image = [UIImage imageNamed: @"7.jpg"];
            
            cell.lable.text = @"夜间模式";
            break;
            
            case 1:
            cell.view.image = [UIImage imageNamed: @"baidu"];
            
            cell.lable.text = @"软件应用";
            break;
        case 2:
            cell.view.image = [UIImage imageNamed: @"yy.jpg"];
            
            cell.lable.text = @"美女写真";

            break;
        case 3:
            cell.view.image = [UIImage imageNamed: @"弹弓.jpg"];
            
            cell.lable.text = @"弹弓怪兽";

            break;
        case 4:
            
            cell.view.image = [UIImage imageNamed: @"yyyy.jpg"];
            
            cell.lable.text = @"YY直播间";
            break;
        case 5:
            cell.view.image = [UIImage imageNamed: @"bala.jpg"];
            
            cell.lable.text = @"Music";
            break;
        case 6:
            cell.view.image = [UIImage imageNamed: @"12.jpg"];
            
            cell.lable.text = @"清除缓存";

            break;
        case 7:
            cell.view.image = [UIImage imageNamed: @"11.jpg"];
            
            cell.lable.text = @"更多期待";

            break;
            
            
        default:
            break;
    }
    
    
      return cell;
    
    
}
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    
    
    switch (indexPath.row) {
        case 0:
            //夜间模式
            [ThemeManage shareThemeManage].isNight = ![ThemeManage shareThemeManage].isNight;
            [[NSNotificationCenter defaultCenter] postNotificationName:@"changeColor" object:nil];
            [[NSUserDefaults standardUserDefaults] setBool:[ThemeManage shareThemeManage].isNight forKey:@"night"];
            break;
        case 1:
        {
            BaiduViewController *baidu =[BaiduViewController new];
            
            baidu.title = @"百度手机应用助手";
            [self.navigationController pushViewController:baidu animated:YES];
        }
            break;
        case 2:{
            BeautiyViewController *beauty =[[BeautiyViewController alloc] init];
            
            
            beauty.title = @"美女写真";
            [self.navigationController pushViewController:beauty animated:YES];
            
        }
            
            break;
        case 3:{
        
            PLayViewController *play =[PLayViewController new];
            
            play.title = @"弹弓怪兽-豆豆游戏";
            [self.navigationController pushViewController:play animated:YES];


            
        }
            
            break;
        case 4:{
          
            
            YYViewController *yy =[YYViewController new];
            yy.title = @"YY直播间";
            [self.navigationController pushViewController:yy animated:YES];

            
                  }
         
            
            break;
        case 5:
        {
            MusicsViewController *music =[MusicsViewController new];
            
            
            music.title = @"再不疯狂,我们就老了";
            [self.navigationController pushViewController:music animated:YES];

        }
            
            break;
        case 6:{
            
            //调用第三方方法
            
            float ImageCache = [[SDImageCache sharedImageCache]getSize]/1000/1000;
            
            NSString * CacheString = [NSString stringWithFormat:@"缓存大小为%.2fM.确定要清理缓存么?",ImageCache];
            
            
            UIAlertController *alert =[UIAlertController alertControllerWithTitle:@"提示" message:CacheString preferredStyle:(UIAlertControllerStyleAlert)];
            
            
            UIAlertAction *action  =[UIAlertAction actionWithTitle:@"取消" style:(UIAlertActionStyleCancel) handler:^(UIAlertAction * _Nonnull action) {
                
                
                
            } ];
            
            UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"确定" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
                
                
                
                [self clearDisk];
                
                
                
                
                [[SDImageCache sharedImageCache] clearDisk];
            }];
            
            
            [alert addAction:action];
            
            [alert addAction:action1];
            
            [self presentViewController:alert animated:YES completion:nil];
            
            
        }
            
            break;
        case 7:
        {
            [NSObject alterString:@"更多功能,敬请期待!"];

        }
            
            break;
            
        default:
            break;
    }
            
}

//登录时换成用户名
-(void)load
{
    
    [_loadButton setTitle:[loadShare shareLoad].userName forState:(UIControlStateNormal)];
    _loadButton.userInteractionEnabled = NO;
    
}
//退出
-(void)logout
{
    _imageView.image =[UIImage imageNamed:@"man"];
    [_loadButton setTitle:@"立即登录" forState:(UIControlStateNormal)];
    _loadButton.userInteractionEnabled = YES;

    
   }

//清除缓存
-(void)Action

{
    
    
}
//清除缓存
-(void)clearDisk{
    
    NSString *libpath =  [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES)lastObject];
    //初始化文件管理者
    NSFileManager *mar = [NSFileManager defaultManager];
    //获取lib文件下的所有子路径
    NSArray *libSupaths = [mar subpathsAtPath:libpath];
    //遍历所有子路径
    for (NSString *iter in libSupaths) {
        if (![iter containsString:@"Preferences"]) {
            
            
            //把路径拼接全
            NSString *path = [libpath stringByAppendingPathComponent:iter];
            //删除文件
            [mar removeItemAtPath:path error:nil];
            
        }
    }
    
    
}
//获取硬盘大小
-(CGFloat)getDiskSize{
    
    NSString *libpath =  [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES)lastObject];
    //初始化文件管理者
    NSFileManager *mar = [NSFileManager defaultManager];
    //获取lib文件下的所有子路径
    NSArray *libSupaths = [mar subpathsAtPath:libpath];
    //遍历所有子路径
    NSInteger size =0;
    for (NSString *iter in libSupaths) {
        if (![iter containsString:@"Preferences"]) {
            
            
            //把路径拼接全
            NSString *path = [libpath stringByAppendingPathComponent:iter];
            //获取文件的所有信息
            NSDictionary *iteAttr =[mar attributesOfItemAtPath:path error:nil];
            //获取文件的大小
            size +=  [iteAttr[@"NSFileSize"] integerValue];
        }
    }
    return size/1024.0/1024.0;
}


//立即登录跳转
-(void)loadAction
{
    LoadViewController *load =[LoadViewController new];
    
    load.title =@"登录";
    
    [self.navigationController pushViewController:load animated:YES];
    
    
    
    
    
}



-(void)Action:(UIBarButtonItem *)sender
{
    
    if ([loadShare shareLoad].load == YES) {
        
        
        [AVUser logOut];
        
        
        UIAlertController *alert =[UIAlertController alertControllerWithTitle:@"提示" message:@"账号退出成功" preferredStyle:UIAlertControllerStyleAlert];
        
        UIAlertAction *action =[UIAlertAction actionWithTitle:@"取消" style:(UIAlertActionStyleCancel) handler:nil];
        
        UIAlertAction *action1 =[UIAlertAction actionWithTitle:@"确定" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
            
            [self logout];

            
           
        }];
        
        [alert addAction:action];
        [alert addAction:action1];
        [self presentViewController:alert animated:YES completion:nil];
        
      
    }else{
        
        
        NSLog(@"111");
    }
   
        
    
    
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
